package vn.gq.cd.adutils;

import vn.gq.cd.model.bean.AdmobItem;
import android.app.Activity;
import android.util.Log;
import com.google.ads.Ad;
import com.google.ads.AdListener;
import com.google.ads.AdRequest;
import com.google.ads.AdRequest.ErrorCode;
import com.google.ads.InterstitialAd;
import com.google.ads.mediation.inmobi.InMobiAdapterExtras;

public class IntersitialHelper {

	private static final String TAG = "IntersitialHelper";
	
	private InterstitialAd intersitialAd;
	private AdmobItem admobItem;
	private IntersititalAdType adType;
	private IntersitialAdListener intersitialAdListener = new IntersitialAdListener();
	
	public enum IntersititalAdType {
		INTERSITIAL, O_INTERSITIAL
	}
	
	public IntersitialHelper(Activity activity, AdListener listener) {
		this(activity, listener, IntersititalAdType.INTERSITIAL);
	}
	
	public IntersitialHelper(Activity activity, AdListener listener, IntersititalAdType type) {
		admobItem = AdmobItem.load(activity.getApplicationContext());
		String adUnitId = (type == IntersititalAdType.INTERSITIAL) ? admobItem.getAdTypeIntersitial() : admobItem.getAdTypeOIntersitial();
		intersitialAd = new InterstitialAd(activity, adUnitId);
		intersitialAd.setAdListener((listener == null) ? intersitialAdListener : listener);
		adType = type;
	}
	
	public void loadAd(boolean loadIMAd) {
		AdRequest adRequest = new AdRequest();
		if (loadIMAd || (adType == IntersititalAdType.O_INTERSITIAL)) {
			InMobiAdapterExtras inMobiExtra = new InMobiAdapterExtras();
			inMobiExtra.setIncome(65000);
			adRequest.setNetworkExtras(inMobiExtra);
		}
		intersitialAd.loadAd(adRequest);
	}
	
	public void loadAd() {
		loadAd(false);
	}
	
	public void show() {
		if (intersitialAd != null) {
			intersitialAd.show();
		}
	}
	
	public void setAdListener(AdListener adListener) {
		intersitialAd.setAdListener(adListener);
	}
	
	public class IntersitialAdListener implements AdListener {

		@Override
		public void onDismissScreen(Ad ad) {
		}

		@Override
		public void onFailedToReceiveAd(Ad ad, ErrorCode e) {
			
		}

		@Override
		public void onLeaveApplication(Ad ad) {
			
		}

		@Override
		public void onPresentScreen(Ad ad) {
			
		}

		@Override
		public void onReceiveAd(Ad ad) {
			if (ad.isReady()) {
				((InterstitialAd) ad).show();
			}
		}
		
	}
}
